import Header from './components/Header'
import Footer from './components/Footer'
import List from './components/List'
import { Component } from 'react'

export default class App extends Component {
  state = {
    todos: [
      { id: '001', name: '吃饭', done: false },
      { id: '002', name: '睡觉', done: true },
      { id: '003', name: '敲代码', done: false },
      { id: '004', name: '逛街', done: true },
    ],
  }

  // 状态在哪里  操作的方法就在哪里   单向数据流~

  addTask = taskObj => {
    this.setState({
      todos: [taskObj, ...this.state.todos],
    })
  }

  changeChecked = (id, checked) => {
    // console.log('App', id, checked)
    this.state.todos.forEach(item => {
      if (item.id === id) {
        item.done = checked
      }
    })
    this.setState({ todos: this.state.todos })
  }

  delTodo = id => {
    const newTodos = this.state.todos.filter(item => item.id !== id)
    this.setState({ todos: newTodos })
  }

  checkAll = bool => {
    const newTodos = this.state.todos.map(item => {
      return { ...item, done: bool }
    })
    this.setState({ todos: newTodos })
  }

  handleClearAll = () => {
    const newTodos = this.state.todos.filter(item => !item.done)
    this.setState({ todos: newTodos })
  }

  render() {
    const { todos } = this.state
    return (
      <section className="todoapp">
        <Header addTask={this.addTask}></Header>
        <List
          todos={todos}
          changeChecked={this.changeChecked}
          delTodo={this.delTodo}
          checkAll={this.checkAll}
        ></List>
        <Footer todos={todos} handleClearAll={this.handleClearAll}></Footer>
      </section>
    )
  }
}
